import { sequelize, User } from '../models'

/**
 * 微信小程序登陆
 * @param {string} openId
 * @param {string} accessToken
 */
export const wxLogin = async (openId, accessToken, unionId) => {
  return sequelize.transaction(async t => {
    let user = null
    if (!user && unionId) {
      user = await User.findOne(
        {
          where: { unionId }
        },
        { transaction: t }
      )
    }
    if (!user && openId) {
      user = await User.findOne(
        {
          where: { openId }
        },
        {
          transaction: t
        }
      )
    }
    if (user) {
      user.openId = openId
      user.unionId = unionId
      user.accessToken = accessToken
      await user.save({ transaction: t })
    } else {
      user = await User.create(
        { openId, accessToken, unionId, source: 'wechat' },
        {
          transaction: t
        }
      )
    }
    return user
  })
}

/**
 * 用户绑定身份的时候更新基本的微信信息
 * @param {int} userId
 * @param {string} roles
 * @param {object} userInfo
 */
export const updateWxUserInfo = async (userId, userInfo) => {
  return sequelize.transaction(async t => {
    let user = await User.findById(userId, { transaction: t })
    if (!user) {
      throw new Error(`${ERRORS.DBERR.ERR_RECORD_NOT_FOUND}`)
    }
    user.nickName = userInfo.nickName
    user.gender = userInfo.gender
    user.city = userInfo.city
    user.province = userInfo.province
    user.country = userInfo.country
    user.avatarUrl = userInfo.avatarUrl
    await user.save({ transaction: t })
    return user
  })
}

/**
 * 更新用户的profile
 * @param {int} userId
 * @param {string} roles
 * @param {object} userInfo
 */
export const updateUserProfile = async (userId, profile) => {
  return sequelize.transaction(async t => {
    const user = await User.findById(userId, { transaction: t })
    if (!user) {
      throw new Error(`${ERRORS.DBERR.ERR_RECORD_NOT_FOUND}`)
    }
    user.nickName = profile.nickName
    user.avatarUrl = profile.avatarUrl
    if (profile.roles) {
      user.roles = profile.roles
    }
    await user.save({ transaction: t })
    return user
  })
}

/**
 * 测试账号登录
 * @param {string} email
 * @param {string} password
 * @param {string} source
 */
export const testLogin = async (email, password) => {
  return sequelize.transaction(async t => {
    let users = await User.findOrCreate({
      where: { openId: email },
      defaults: { openId: email, accessToken: password, source: 'email' },
      transaction: t
    })
    return users[0]
  })
}
